package org.ptkparty.client.activity;

import java.util.List;

import org.ptkparty.client.ClientFactory;
import org.ptkparty.client.Context;
import org.ptkparty.client.model.PlaceProxy;
import org.ptkparty.client.model.UserProxy;
import org.ptkparty.client.place.ShowGamesPlace;
import org.ptkparty.client.view.games.PrepareGamesView;

import com.google.gwt.activity.shared.Activity;
import com.google.gwt.event.shared.EventBus;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.AcceptsOneWidget;
import com.google.web.bindery.requestfactory.shared.Receiver;

public class PrepareGamesActivity implements Activity {

	private ClientFactory clientFactory;
	private PrepareGamesView view;

	public PrepareGamesActivity(ClientFactory clientFactory, String currentChampionship) {
		this.clientFactory = clientFactory;
		Context.get().setCurrentChampionship(currentChampionship);
	}

	@Override
	public void start(AcceptsOneWidget panel, final EventBus eventBus) {
		view = clientFactory.getPrepareGameView();
		view.setPresenter(this);
		panel.setWidget(view);

		clientFactory.getFactory().userRequest().getUsersByChampionship(Context.get().getCurrentChampionship()).fire(new Receiver<List<UserProxy>>() {

			@Override
			public void onSuccess(List<UserProxy> response) {
				view.loadUser(response);

				clientFactory.getFactory().placeRequest().getAll().fire(new Receiver<List<PlaceProxy>>() {

					@Override
					public void onSuccess(List<PlaceProxy> response) {
						view.loadPlaces(response);
					}

				});
			}

		});

	}

	@Override
	public String mayStop() {
		return null;
	}

	@Override
	public void onCancel() {
	}

	@Override
	public void onStop() {
	}

	public void generate(String boulodrome, List<String> players) {
		clientFactory.getPtkService().generateGames(Context.get().getCurrentChampionship(), boulodrome, players, new AsyncCallback<Boolean>() {

			@Override
			public void onFailure(Throwable caught) {
				view.showError(caught.getMessage());
			}

			@Override
			public void onSuccess(Boolean result) {
				clientFactory.getPlaceController().goTo(new ShowGamesPlace(Context.get().getCurrentChampionship()));
			}
		});
	}

}
